const db = require('../config/database');
const logger = require('../utils/logger');

class CategoryController {
  // 获取商品分类列表（前台）
  async getCategories(req, res) {
    try {
      const [categories] = await db.query(
        'SELECT id, name, icon, description FROM product_categories WHERE status = 1 ORDER BY sort_order ASC'
      );

      res.json({
        success: true,
        data: categories
      });
    } catch (error) {
      logger.error('获取分类列表失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取商品分类列表（后台管理）
  async getCategoriesAdmin(req, res) {
    try {
      const { page = 1, pageSize = 9999, status } = req.query;
      const offset = (page - 1) * pageSize;

      let sql = 'SELECT * FROM product_categories WHERE 1=1';
      const params = [];

      if (status !== undefined) {
        sql += ' AND status = ?';
        params.push(status);
      }

      sql += ' ORDER BY sort_order ASC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [categories] = await db.query(sql, params);

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM product_categories WHERE 1=1';
      const countParams = [];

      if (status !== undefined) {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: categories,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取分类列表失败（后台）', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 创建商品分类（后台管理）
  async createCategory(req, res) {
    try {
      const { name, icon, description, sort_order = 0 } = req.body;

      if (!name) {
        return res.json({
          success: false,
          message: '分类名称不能为空'
        });
      }

      // 检查分类名称是否已存在
      const [existing] = await db.query(
        'SELECT id FROM product_categories WHERE name = ?',
        [name]
      );

      if (existing.length > 0) {
        return res.json({
          success: false,
          message: '分类名称已存在'
        });
      }

      const [result] = await db.query(
        `INSERT INTO product_categories (name, icon, description, sort_order, status, created_at, updated_at) 
         VALUES (?, ?, ?, ?, 1, NOW(), NOW())`,
        [name, icon || null, description || null, sort_order]
      );

      logger.success('创建分类成功', { id: result.insertId, name });

      res.json({
        success: true,
        message: '创建成功',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('创建分类失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 更新商品分类（后台管理）
  async updateCategory(req, res) {
    try {
      const { id } = req.params;
      const { name, icon, description, sort_order, status } = req.body;

      const updates = [];
      const values = [];

      if (name !== undefined) {
        // 检查名称是否与其他分类冲突
        const [existing] = await db.query(
          'SELECT id FROM product_categories WHERE name = ? AND id != ?',
          [name, id]
        );

        if (existing.length > 0) {
          return res.json({
            success: false,
            message: '分类名称已存在'
          });
        }

        updates.push('name = ?');
        values.push(name);
      }

      if (icon !== undefined) {
        updates.push('icon = ?');
        values.push(icon);
      }

      if (description !== undefined) {
        updates.push('description = ?');
        values.push(description);
      }

      if (sort_order !== undefined) {
        updates.push('sort_order = ?');
        values.push(sort_order);
      }

      if (status !== undefined) {
        updates.push('status = ?');
        values.push(status);
      }

      if (updates.length === 0) {
        return res.json({
          success: false,
          message: '没有要更新的内容'
        });
      }

      values.push(id);

      const [result] = await db.query(
        `UPDATE product_categories SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`,
        values
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '分类不存在'
        });
      }

      logger.success('更新分类成功', { id });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新分类失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 删除商品分类（后台管理）
  async deleteCategory(req, res) {
    try {
      const { id } = req.params;

      // 检查该分类下是否有商品
      const [products] = await db.query(
        'SELECT COUNT(*) as count FROM products WHERE category_id = ?',
        [id]
      );

      if (products[0].count > 0) {
        return res.json({
          success: false,
          message: '该分类下存在商品，无法删除'
        });
      }

      const [result] = await db.query(
        'DELETE FROM product_categories WHERE id = ?',
        [id]
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '分类不存在'
        });
      }

      logger.success('删除分类成功', { id });

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error) {
      logger.error('删除分类失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取分类详情
  async getCategoryDetail(req, res) {
    try {
      const { id } = req.params;

      const [categories] = await db.query(
        'SELECT * FROM product_categories WHERE id = ?',
        [id]
      );

      if (categories.length === 0) {
        return res.json({
          success: false,
          message: '分类不存在'
        });
      }

      res.json({
        success: true,
        data: categories[0]
      });
    } catch (error) {
      logger.error('获取分类详情失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new CategoryController();

